<?php
require_once 'Interface.php';
require_once 'Result/Mysql.php';
class Simpple_Model_Mysql implements Simpple_Model_Interface {
	private static $_options;
	private static $_mysql;
	
	protected $link;
	
	private function __construct($link) {
		$this->link = $link;
	}
	
	/**
	 * 设置默认选项
	 *
	 * @param array $options
	 */
	public static function setDefaultOptions($options){
		self::$_options = $options;
	}
	
	/**
	 * 获取mysql实例
	 *
	 * @param array $options
	 * @return Simpple_Model_Mysql
	 */
	public static function getMysql($options=null) {
		if (self::$_mysql == null) {
			if ($options == null) {
				$options = self::$_options;
			}
			if (empty($options)) {
				throw new Simpple_Model_Exception("no options supplied");
			}
			
			$link = self::factory($options);
			
			self::$_mysql = new Simpple_Model_Mysql($link);
		}
		return self::$_mysql;
	}
	
	/**
	 * 创建mysql资源
	 *
	 * @param array $options
	 * @return resource
	 */
	public static function factory($options) {
		$arr = array('host','user','pass','dbname','charset');
		foreach($arr as $key) {
			$$key = isset($options[$key]) ? $options[$key] : '';
		}
		$link = mysql_connect($host, $user, $pass);
		mysql_select_db($dbname, $link);
		mysql_query("set names {$charset}");
		return $link;
	}

	/**
	 * 关闭连接
	 *
	 */
	public function close() {
		mysql_close($this->link);
	}
	
	public function __destruct() {
		$this->close();
	}

	/**
	*
	* @return Simpple_Model_Result_Mysql
	*/
	public function query($sql) {
		$ret = $this->execute($sql);
		if (mysql_errno() > 0) {
			throw new Exception(mysql_error());
		}
		return new Simpple_Model_Result_Mysql($ret);
	}

	/**
	 * 执行sql语句
	 *
	 * @param string $sql
	 * @return resource
	 */
	public function execute($sql) {
		return mysql_query($sql, $this->link);
	}

	/**
	 * 获取单一的数据	
	 *
	 * @param string $sql
	 * @return mixed
	 */
	public function getOne($sql) {
		$rs = $this->query($sql);
		if ($rs->hasNext()) {
			$ret = $rs->getNext();
			return array_shift($ret);
		}
		return false;
	}

	/**
	 * 取出一行数据
	 *
	 * @param string $sql
	 * @return array
	 */
	public function getRow($sql) {
		$rs = $this->query($sql);
		if ($rs->hasNext()) {
			return $rs->getNext();
		}
	}


	/**
	 * 插入数据
	 *
	 * @param string $table
	 * @param array $data
	 * @return int | false
	 */
	public function insert($table, $data) {
		$rows = array();
		$columns = array();
		$values = array();
		foreach($data as $key=>$value) {
			$columns[$key] = "`".$key."`";
			if (!is_numeric($value)) {
				$values[$key] = "'".$this->escape($value)."'";
			} else {
				$values[$key] = $value;
			}
		}
		$sql = "INSERT INTO `{$table}`(".implode(',', $columns).") VALUES(".implode(',', $values).")";
		$this->query($sql);
		if ($this->getAffectedRows() == 1) {
			return $this->getLastId();
		}
		return false;
	}

	/**
	 * 构建where查询
	 *
	 * @param array $options
	 * @return string
	 */
	public function buildWhere($options) {
		$ret = array();
		foreach($options as $key=>$value) {
			if (!preg_match("/[`()]+/", $key)) {
				$key = "`".$key."`";
			}
			if (!is_numeric($value)) {
				$value = "'".$this->escape($value)."'";
			}
			$ret[] = "({$key}={$value})";
		}
		return implode(" AND ", $ret);
	}
	
	/**
	 * 格式化where查询
	 * @example formatWhere('begin_time >= ?', 3),返回值为 `begin_time`>=3
	 * @param string $statement
	 * @param mixed $value
	 * @return string
	 */
	public function formatWhere($statement, $value) {
		if (strpos($statement,'?') === false) {
			return $statement;
		}
		
	}

	/**
	 * 格式化字符串
	 *
	 * @param string $ori
	 * @return string
	 */
	private function escape($ori) {
		return mysql_escape_string($ori);
	}
	
	/**
	 * 获取受影响的行数
	 *
	 * @return int
	 */
	public function getAffectedRows() {
		return mysql_affected_rows($this->link);
	}

	/**
	 * 获取最后一个受影响的id
	 *
	 * @return int
	 */
	public function getLastId() {
		return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
	}
	
	/**
	 * 获取mysql的错误
	 *
	 * @return string
	 */
	public function getError() {
		return (($this->link) ? mysql_error($this->link) : mysql_error());
	}
	
	/**
	 * 获取mysql的错误码
	 *
	 * @return int
	 */
	function getErrno() {
		return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
	}
	
	/**
	 * 获取mysql的版本号
	 *
	 * @return number
	 */
	function getVersion() {
		return mysql_get_server_info($this->link);
	}
}